<template>
  <el-dialog v-model="visible" :title="`${mode === 'add' ? '新增' : '编辑'}教师`" width="50%" top="5vh">
    <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="教师姓名" prop="name">
            <el-input v-model="form.teacherName" placeholder="请输入教师姓名" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="性别" prop="gender">
            <el-radio-group v-model="form.gender">
              <el-radio value="1">男</el-radio>
              <el-radio value="0">女</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="年龄" prop="age">
            <el-input-number v-model="form.age" :min="18" :max="70" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系方式" prop="phone">
            <el-input v-model="form.phone" placeholder="请输入联系方式" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="专长乐器" prop="instruments">
            <el-select v-model="form.instruments" multiple placeholder="请选择专长乐器" style="width: 100%">
              <el-option v-for="item in props.instrumentsOptions" :key="item.id" :label="item.icName"
                :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="教学级别" prop="level">
            <el-select v-model="form.level" placeholder="请选择教学级别">
              <el-option label="初级教师" value="1" />
              <el-option label="中级教师" value="2" />
              <el-option label="高级教师" value="3" />
              <el-option label="特级教师" value="4" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="电子邮箱" prop="email">
        <el-input v-model="form.email" placeholder="请输入电子邮箱" />
      </el-form-item>

      <el-form-item label="联系地址" prop="address">
        <el-input v-model="form.address" placeholder="请输入联系地址" />
      </el-form-item>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="入职日期" prop="joinDate">
            <el-date-picker v-model="form.joinDate" type="date" placeholder="选择入职日期" value-format="YYYY-MM-DDTHH:mm:ss"
              style="width: 100%" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="form.status">
              <el-radio value="1">在职</el-radio>
              <el-radio value="0">离职</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="头像" prop="avatar">
        <el-upload class="avatar-uploader" action="/api/upload" :headers="{ 'Authorization': `Bearer ${getToken()}` }"
          :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
          <img v-if="form.avatar" :src="form.avatar" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>

      <el-form-item label="教师简介" prop="description">
        <el-input v-model="form.description" type="textarea" :rows="4" placeholder="请输入教师简介" />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="submitForm">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { getToken } from '@/utils/auth'

const props = defineProps({
  modelValue: Boolean,
  teacherData: Object,
  mode: String, // 'add' or 'edit'
  instrumentsOptions: Array
})


const emit = defineEmits(['update:modelValue', 'success'])

const visible = ref(false)
const formRef = ref(null)

// 表单数据
const form = reactive({
  teacherName: '',
  gender: '1',
  age: 30,
  phone: '',
  instruments: [],
  level: '2',
  email: '',
  address: '',
  joinDate: '',
  status: '1',
  avatar: '',
  description: ''
})

// 表单验证规则
const rules = {
  teacherName: [{ required: true, message: '请输入教师姓名', trigger: 'blur' }],
  gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
  phone: [
    { required: true, message: '请输入联系方式', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  instruments: [{ required: true, message: '请选择专长乐器', trigger: 'change' }],
  level: [{ required: true, message: '请选择教学级别', trigger: 'change' }],
  email: [
    { required: true, message: '请输入电子邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  joinDate: [{ required: true, message: '请选择入职日期', trigger: 'change' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

// 监听显示状态
watch(() => props.modelValue, (val) => {
  visible.value = val
  if (val && props.mode === 'edit' && props.teacherData) {
    Object.assign(form, props.teacherData)
  } else if (val && props.mode === 'add') {
    resetForm()
  }
})

watch(visible, (val) => {
  emit('update:modelValue', val)
})

// 头像上传成功处理
const handleAvatarSuccess = (response, file) => {
  console.log(response, URL.createObjectURL(file.raw))
  form.avatar = response.data
}

// 头像上传前校验
const beforeAvatarUpload = (file) => {
  const isImage = file.type.includes('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('您上传的不是图片!')
  }
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 2MB!')
  }
  return isImage && isLt2M
}
// 重置表单
const resetForm = () => {
  formRef.value?.resetFields()
  Object.assign(form, {
    teacherName: '',
    gender: '1',
    age: 30,
    phone: '',
    instrument: 'piano',
    level: '2',
    email: '',
    address: '',
    joinDate: '',
    status: '1',
    avatar: '',
    description: ''
  })
}

// 提交表单
const submitForm = async () => {
  try {
    await formRef.value.validate()

    emit('success', form)
    visible.value = false
  } catch (error) {
    console.error('表单验证失败', error)
  }
}
</script>

<style scoped>
.avatar-uploader {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 100px;
  height: 100px;
}

.avatar-uploader:hover {
  border-color: var(--el-color-primary);
}

.avatar {
  width: 100%;
  height: 100%;
  display: block;
  object-fit: cover;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
  line-height: 100px;
}
</style>
